package com.xiangyueEducation.uploaderCloud.controller;

import com.xiangyueEducation.uploaderCloud.context.BaseContext;
import com.xiangyueEducation.uploaderCloud.utils.JwtHelper;
import com.xiangyueEducation.uploaderCloud.pojo.entity.Diary;
import com.xiangyueEducation.uploaderCloud.service.entity.DiaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/diaries")
public class DiaryController {

    private final DiaryService diaryService;
    private final JwtHelper jwtHelper;

    @Autowired
    public DiaryController(DiaryService diaryService, JwtHelper jwtHelper) {
        this.diaryService = diaryService;
        this.jwtHelper = jwtHelper;
    }

    // 创建日记接口
    @PostMapping("/create")
    public String createDiary(@RequestBody Diary diary, @RequestHeader String token) {
        // 从 token 中解析 userId
        Long userId = jwtHelper.getUserId(token);
        if (userId == null) {
            return "无效的 token";
        }

        // 设置日记的 userId
        diary.setUserId(Math.toIntExact(userId));

        // 调用 service 层保存日记
        int result = diaryService.createDiary(diary);
        return result > 0 ? "日记创建成功" : "日记创建失败";
    }

    // 根据用户 ID 获取日记
    @GetMapping("/student")
    public List<Diary> getDiariesByUserId() {
        Long userId = BaseContext.getCurrentUser().getId();
        return diaryService.getDiariesByUserId(userId);
    }

    // 获取所有活跃的日记
    @GetMapping("/all")
    public List<Diary> getAllActiveDiaries() {
        return diaryService.getAllActiveDiaries();
    }

    // 根据日记 ID 获取日记
    @GetMapping("/{diaryId}")
    public Diary getDiaryById(@PathVariable Long diaryId) {
        return diaryService.getDiaryById(diaryId);
    }

    // 根据日期范围获取日记
    @GetMapping("/date-range")
    public List<Diary> getDiariesByDateRange(@RequestParam String startTime, @RequestParam String endTime) {
        return diaryService.getDiariesByDateRange(startTime, endTime);
    }

    // 根据关键词搜索日记
    @GetMapping("/search/{keyword}")
    public List<Diary> getDiariesByKeyword(@PathVariable String keyword) {
        return diaryService.getDiariesByKeyword(keyword);
    }
}
